package com.xxwy.simple.rpc.server;

import com.xxwy.simple.apply.provider.HelloServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author wy
 * @date 2020/3/9 10:26
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    //获取客户端发送的消息，并调用服务
    System.out.println(msg);
    //客户端在调用服务的api时，需要定义一个协议,每次发消息时都必须以某个 字符串开头
    if(msg.toString().startsWith("HelloServiceImpl#")){
      String words = msg.toString().substring(msg.toString().lastIndexOf("#") + 1);
      String hello = new HelloServiceImpl().hello(words);
      ctx.writeAndFlush(hello);
    }
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
    cause.printStackTrace();
  }
}
